package com.study.cloud.config;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

@Component
public class RequestTimeFilter implements GlobalFilter, Ordered {

    Logger log = LoggerFactory.getLogger(RequestTimeFilter.class);

    /**
     * 追踪traceID
     */
    public final static String TRACE_ROOT_ID = "traceRootId";

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put("hello",System.currentTimeMillis());


        String traceRootId = UUID.randomUUID().toString().replace("-","");
        MDC.put(TRACE_ROOT_ID,traceRootId);
        exchange.getRequest().mutate().header(TRACE_ROOT_ID,traceRootId);


        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    Long startTime = exchange.getAttribute("hello");
                    if (startTime != null) {
                        log.info(exchange.getRequest().getURI().getRawPath() + ": " + (System.currentTimeMillis() - startTime) + "ms");
                    }
                })
        );
    }
}
